import datetime
import requests
import json
import time
class EarthquakeFetcher:
    def __init__(self, days=7, longitude_range=(73.66, 135.05), latitude_range=(3.86, 53.55), magnitude=0):
        self.url = "http://api.dizhensubao.getui.com/api.htm"
        self.days = days
        self.longitude_range = longitude_range
        self.latitude_range = latitude_range
        self.magnitude = magnitude

    def timeStamp(self, timeNum):
        timeStamp = float(timeNum/1000)
        timeArray = time.localtime(timeStamp)
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        return otherStyleTime

    def fetch_data(self):
        seconds_per_day = 86400
        start_time = int(round((time.time() - self.days * seconds_per_day) * 1000))
        data = {"action": "requestMonitorDataAction", "startTime": start_time, "dataSource": "CEIC"}
        data_json = json.dumps(data)
        res = requests.post(self.url, data_json)
        earthquake_json = json.loads(res.text)
        data = earthquake_json["values"]

        filtered_data = [earthquake for earthquake in data
                         if self.longitude_range[0] <= earthquake['longitude'] <= self.longitude_range[1]
                         and self.latitude_range[0] <= earthquake['latitude'] <= self.latitude_range[1]
                         and earthquake['mag'] >= self.magnitude]

        earthquake_list = []

        for earthquake in filtered_data:
            # 创建一个字典来保存这次地震的信息
            earthquake_dict = {
                'location': earthquake['loc_name'],
                'time': self.timeStamp(earthquake['time']),
                'magnitude': earthquake['mag'],
                'longitude': earthquake['longitude'],
                'latitude': earthquake['latitude'],
                'depth': earthquake['depth'] / 1000
            }

            # 将这次地震的信息添加到列表中
            earthquake_list.append(earthquake_dict)

        # 循环结束后，将地震列表转换为 JSON 格式
        # earthquake_json = json.dumps(earthquake_list, ensure_ascii=False)
        return earthquake_list

    def str_to_datetime(self, timestr):
        return datetime.datetime.strptime(timestr, "%Y-%m-%d %H:%M:%S")

    def monitor_earthquakes(self, interval=5):
        latest_earthquake = None
        while True:
            filtered_data = self.fetch_data()
            # print(filtered_data)
            if filtered_data:
                if latest_earthquake is None or self.str_to_datetime(filtered_data[0]['time']) > self.str_to_datetime(latest_earthquake['time']):
                    latest_earthquake = filtered_data[0]
                    earthquake_dict = {
                        'location': latest_earthquake['location'],
                        'time': latest_earthquake['time'],
                        'magnitude': latest_earthquake['magnitude'],
                        'longitude': latest_earthquake['longitude'],
                        'latitude': latest_earthquake['latitude'],
                        'depth': latest_earthquake['depth']
                    }
                    # earthquake_json = json.dumps(earthquake_dict, ensure_ascii=False)
                    print(earthquake_dict)
            time.sleep(interval)